# app/routes/users_route.rb
require "roda"
#require "json/add/core"
require 'json'
require './app/services/user_service'
require 'pp'

class UsersRoute < Roda
  # 返回正确编码
  plugin :hooks
  before do
    response['Content-Type'] = 'application/json; charset=utf-8'
  end
  # 会自动添加Content-Type,然后返回数据不要.to_json
  #plugin :json
  route do |r|
    r.on 'users' do
      r.is do
        # 获取所有用户
        r.get do
          allData=UserService.get_all_users 
          puts allData.inspect
          pp allData
          puts allData.class
          p allData
          json_data =allData.to_json
          puts json_data
          #allData.as_json.to_json
          puts Encoding.default_external
          puts Encoding.default_internal
          #allData.map(&:values).to_json
          #JSON.generate(allData.map(&:values), encoding: 'UTF-8')
		  allData.map(&:values).to_json
        end

        # 创建用户
        r.post do
          user = UserService.create_user(r.params)
          { success: true, user_id: user.id }.to_json
        end
      end

      # 单个用户操作
      r.on Integer do |id|
        # 获取用户
        r.get do
          user = UserService.find_user_by_id(id)
          user ? user.to_json : { error: 'User not found' }.to_json
        end

        # 更新用户
        r.put do
          user = UserService.update_user(id, r.params)
          user ? { success: true }.to_json : { error: 'User not found' }.to_json
        end

        # 删除用户
        r.delete do
          UserService.delete_user(id)
          { success: true }.to_json
        end
      end
    end
  end
end